package me.zhengjie.modules.device.service.impl;

import me.zhengjie.modules.device.domain.PeopleDevice;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.device.repository.PeopleDeviceRepository;
import me.zhengjie.modules.device.service.PeopleDeviceService;
import me.zhengjie.modules.device.service.dto.PeopleDeviceDTO;
import me.zhengjie.modules.device.service.mapper.PeopleDeviceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;

/**
* @author 张鹏
* @date 2019-05-07
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class PeopleDeviceServiceImpl implements PeopleDeviceService {

    @Autowired
    private PeopleDeviceRepository peopleDeviceRepository;

    @Autowired
    private PeopleDeviceMapper peopleDeviceMapper;

    @Override
    public PeopleDeviceDTO findById(Long id) {
        Optional<PeopleDevice> peopleDevice = peopleDeviceRepository.findById(id);
        ValidationUtil.isNull(peopleDevice,"PeopleDevice","id",id);
        return peopleDeviceMapper.toDto(peopleDevice.get());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PeopleDeviceDTO create(PeopleDevice resources) {
        return peopleDeviceMapper.toDto(peopleDeviceRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(PeopleDevice resources) {
        Optional<PeopleDevice> optionalPeopleDevice = peopleDeviceRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalPeopleDevice,"PeopleDevice","id",resources.getId());

        PeopleDevice peopleDevice = optionalPeopleDevice.get();
        // 此处需自己修改
        resources.setId(peopleDevice.getId());
        peopleDeviceRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        peopleDeviceRepository.deleteById(id);
    }
}